package com.gate.way.demo.config;

import com.gate.way.demo.filter.CustomFilter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

/**
 * 自定义路由--编码方式
 * 也可以通过yaml 配置形式
 * @author wangzhilong
 * @date 2021/3/18
 */
@Configuration
public class RouterConfig {

    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder locatorBuilder) {
        return locatorBuilder.routes()
                .route(p -> p.path("/vega")
                        .filters(f -> f.stripPrefix(1)
                                //某种路由和GateWayFilter过滤器绑定使用
                                .filter(new CustomFilter())
                        )
                        //类似重定向流量了
                        .uri("http://www.baidu.com")
                )
                .route(p ->
                        p.path("/go")
                                .filters(f -> f.stripPrefix(1))
                                .uri("lb://ucenter-v1")
                ).build();
    }

    /**
     * WebFlux 路由方式
     * @return
     */
    @Bean
    public RouterFunction routerFunction(){
        return RouterFunctions.route(
                RequestPredicates.path("/003"),
                request -> ServerResponse.ok().body(BodyInserters.fromValue("ok"))
        );
    }

}
